package com.health.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * 阿里云文件上传服务
 */
@Slf4j
public class AliOssUtil {

    private static final String endpoint = "oss-cn-beijing.aliyuncs.com"; //区域
    private static final String accessKeyId = "LTAI5tGK5YJFWRQ1AA5esn3L";
    private static final String accessKeySecret = "RBMspXMolbvMG2ePnduEV5yiAshi42";
    private static final String bucketName = "itheima2025"; //桶名称

    /**
     * 上传文件
     */
    @SneakyThrows
    public static String upload(InputStream inputStream, String fileName) {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //判断容器是否存在,不存在就创建
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //设置问公共可读
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }

        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

        // 上传文件
        PutObjectRequest request = new PutObjectRequest(bucketName, fileName, inputStream);
        PutObjectResult result = ossClient.putObject(request);

        if (result != null) {
            log.info("OSS文件上传成功：{}", fileName);
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}

    